package com.cht.sys.security;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;

import com.cht.sys.CommonUtil;

public class MBMSCallbackHandler implements CallbackHandler {

	String username;
	char[] password;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public char[] getPassword() {
		return password;
	}

	public void setPassword(char[] password) {
		this.password = password;
	}

	public MBMSCallbackHandler(String username, char[] password) {
		this.username = username;
		this.password = password;
	}

	public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {

	    CommonUtil.setLog4J("debug", "com.cht.sys.sso", "MBMSCallbackHandler.handle() START");

	    try{
		for (int i = 0; i < callbacks.length; i++) {
			if (callbacks[i] instanceof TextOutputCallback) {
				// display the message according to the specified type
				TextOutputCallback toc = (TextOutputCallback) callbacks[i];
				switch (toc.getMessageType()) {
				case TextOutputCallback.INFORMATION:
					CommonUtil.setLog4J("debug", "com.cht.sys.sso", "MBMSCallbackHandler.handle(): INFO " + toc.getMessage());
					break;
				case TextOutputCallback.ERROR:
					CommonUtil.setLog4J("debug", "com.cht.sys.sso", "MBMSCallbackHandler.handle(): ERROR " + toc.getMessage());
					break;
				case TextOutputCallback.WARNING:
					CommonUtil.setLog4J("debug", "com.cht.sys.sso", "MBMSCallbackHandler.handle(): WARNING " + toc.getMessage());
					break;
				default:
				    CommonUtil.setLog4J("debug", "com.cht.sys.sso", "MBMSCallbackHandler.handle(): default " + toc.getMessage());
					throw new IOException("Unsupported message type: " + toc.getMessageType());
				}
			} else if (callbacks[i] instanceof NameCallback) {
				// prompt the user for a username
				NameCallback nc = (NameCallback) callbacks[i];
				nc.setName(username);
			} else if (callbacks[i] instanceof PasswordCallback) {
				// prompt the user for sensitive information
				PasswordCallback pc = (PasswordCallback) callbacks[i];
				pc.setPassword(password);
			} else {
				throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
			}
		}

	}
	catch(Exception e){
	    CommonUtil.setLog4J("debug", "com.cht.sys.sso", "MBMSCallbackHandler catch: " + e.getStackTrace());
	}

	CommonUtil.setLog4J("debug", "com.cht.sys.sso", "MBMSCallbackHandler.handle() END" );

	}
}
